package com.kstech.ks_gaz01.fragments


import android.view.View
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.blankii.androidlibrary.base.BaseBindingFragment
import com.blankii.androidlibrary.exts.logi
import com.blankii.androidlibrary.exts.logw
import com.blankii.androidlibrary.utils.CalcUtil
import com.chad.library.adapter4.layoutmanager.QuickGridLayoutManager
import com.kstech.ks_gaz01.R
import com.kstech.ks_gaz01.XML_IS_SHOW_PROGRESSBAR_ZT
import com.kstech.ks_gaz01.XML_REALTIME_FLOAT
import com.kstech.ks_gaz01.XML_XS_FZ
import com.kstech.ks_gaz01.XML_XS_RTB
import com.kstech.ks_gaz01.base.FragmentPage
import com.kstech.ks_gaz01.base.HomeViewModel
import com.kstech.ks_gaz01.data.DebugDataBean
import com.kstech.ks_gaz01.data.DebugDataBean.floatDataType
import com.kstech.ks_gaz01.data.DebugDataBean.xmlMap
import com.kstech.ks_gaz01.data.GridSpaceItemDecoration
import com.kstech.ks_gaz01.databinding.FragmentRealTimePartBinding
import com.kstech.ks_gaz01.realTime.ChildFragment
import com.kstech.ks_gaz01.realTime.FloatMultiAdapter
import com.kstech.ks_gaz01.socket.SocketFragmentListener
import com.kstech.ks_gaz01.socket.SocketManagerNew


/**
 * author: blankii
 * created on: 2024/5/8 11:15
 * description: 实时参数界面管理（仿真界面和实时参数）
 */
class RealTimePartFragment :
    BaseBindingFragment<FragmentRealTimePartBinding>(FragmentRealTimePartBinding::inflate),
    SocketFragmentListener {


    private val PAGE_A = "PAGE_A"
    private val PAGE_B = "PAGE_B"

    private val realTimeParaFragment = RealTimeParaFragment()
    private val simulationFragment = SimulationFragment()
    private val ztProgressFragment = ZtProgressFragment()
    private var lastFragment: ChildFragment? = null
    private lateinit var mViewModel: HomeViewModel

    /**
     * floatAdapter
     */
    private lateinit var floatAdapter: FloatMultiAdapter
    private lateinit var floatArray: ArrayList<DebugDataBean.Item>


    private fun addFragment(fragment: ChildFragment, flag: String) {
        val fragmentTransaction: FragmentTransaction = parentFragmentManager.beginTransaction()
        val flagFragment = parentFragmentManager.findFragmentByTag(flag)
        if (lastFragment != null) {
            fragmentTransaction.hide(lastFragment!!)
            lastFragment!!.pageOnPause()
        }
        if (flagFragment == null) {
            fragmentTransaction.add(R.id.childFragment, fragment!!, flag)
        } else {
            fragmentTransaction.show(fragment!!)
            fragment!!.pageOnResume()
        }
        lastFragment = fragment
        fragmentTransaction.commit()
    }

    private fun initView() {
        binding.apply {
            /**
             * 隐藏打开仿真界面开关
             */
            val keyIsExist = DebugDataBean.xmlSettings.contains(XML_XS_FZ)
            if (!keyIsExist) {
                "请检查该车型XML文件 XmlSetting中是否存在 是否显示仿真界面".logw(TAG)
            } else if (!DebugDataBean.xmlSettings[XML_XS_FZ]!!) {
                binding.modelSwitch.visibility = View.GONE
            }
            /**
             * 隐藏打开支腿涨幅开关
             */
            val keyIsExistZt = DebugDataBean.xmlSettings[XML_IS_SHOW_PROGRESSBAR_ZT]
            if (!(keyIsExistZt != null && keyIsExistZt)) {
                binding.modelSwitchZt.visibility = View.GONE
            }
            /**
             * 隐藏并关闭实时参数下边栏
             */
            val keyIsExistRt = DebugDataBean.xmlSettings[XML_XS_RTB]
            if (!(keyIsExistRt != null && keyIsExistRt && floatDataType == "right")) {
                binding.floatPart.visibility = View.GONE
            } else {
                /**
                 * 初始化floatRecyclerView
                 */
                floatArray = ArrayList()
                floatPart.layoutManager = QuickGridLayoutManager(requireActivity(), 7)
                floatAdapter = FloatMultiAdapter(floatArray)
                floatPart.setOnTouchListener(View.OnTouchListener { v, event -> true })
//            floatPart.isNestedScrollingEnabled = false
                floatPart.addItemDecoration(GridSpaceItemDecoration(10, 10))
                floatPart.adapter = floatAdapter
                floatArray.addAll(DebugDataBean.xmlMap[XML_REALTIME_FLOAT]!![0].itemList)
                floatAdapter.notifyDataSetChanged()
            }

            /**
             * Switch 点击事件
             */
            modelSwitch.setOnCheckedChangeListener { buttonView, isChecked ->
                if (isChecked) {
                    //仿真界面
                    addFragment(simulationFragment, PAGE_B)
                } else {
                    //实时参数
                    addFragment(realTimeParaFragment, PAGE_A)
                }
//                currentFragment!!.pageOnResume()
            }
            /**
             * Switch 支腿涨幅 点击事件
             */
            modelSwitchZt.setOnCheckedChangeListener { buttonView, isChecked ->
                if (isChecked) {
                    //仿真界面
                    addFragment(ztProgressFragment, PAGE_B)
                } else {
                    //实时参数
                    addFragment(realTimeParaFragment, PAGE_A)
                }
//                currentFragment!!.pageOnResume()
            }
            /**
             * 监听navController
             */
//            val navController = findNavController()
//            navController.addOnDestinationChangedListener { controller, destination, arguments ->
//                if (destination.id == R.id.homeFragment) {
//                    when (mViewModel.currentPage) {
//                        HomeFragment.ViewPagerPage.CONFIG_PAGE -> {
//                            "执行1${mViewModel.currentPage}".loge(TAG)
//                        }
//
//                        HomeFragment.ViewPagerPage.REALTIME_PAGE -> {
//                            "执行2${mViewModel.currentPage}".loge(TAG)
//
//                        }
//                    }
//                } else {
//                    "执行3${mViewModel.currentPage}".loge(TAG)
//                    SocketManagerNew.unSubscribeSocketFragmentListener()
//                }
//            }

        }
    }


    /**
     * RealTimeParaFragment/SimulationFragment 先onResume
     * 然后本fragment 再onResume
     */
    override fun onResume() {
        super.onResume()
        SocketManagerNew.subscribeSocketFragmentListener(this)
        lastFragment!!.pageOnResume()
    }

    override fun onPause() {
        super.onPause()
        lastFragment!!.pageOnPause()
        SocketManagerNew.unSubscribeSocketFragmentListener()
    }

    override fun onCreateInit() {
        mViewModel = ViewModelProvider(requireActivity())[HomeViewModel::class.java]
    }

    override fun onInitView() {
        /**
         * 初始化fragment
         */
        addFragment(realTimeParaFragment, PAGE_A)
        initView()
        /**
         * 监听ViewModel
         */
        mViewModel.currentPage.observe(this, Observer {
            if (it == FragmentPage.HOME_REALTIME) {
                SocketManagerNew.subscribeSocketFragmentListener(this@RealTimePartFragment)
                lastFragment!!.pageOnResume()
            }
//            else {
//                SocketManagerNew.unSubscribeSocketFragmentListener()
//            }
        })
    }


    override fun writeSuccess(address: String, value: String) {
        lastFragment!!.writeSuccess(address, value)
    }

    override fun readSuccess(address: String, result: ArrayList<String>) {
        if (::floatArray.isInitialized && getFloatFirst() != null && address == (getFloatFirst()!!.para0.toInt() - 1).toString() && result.size == floatArray.size) {
            for (i in floatArray.indices) {
                floatArray[i].revData =
                    CalcUtil.Hex2IntStr(result[i], floatArray[i].isNegativeNumber)
            }
            floatAdapter.notifyDataSetChanged()
        } else {
            lastFragment!!.readSuccess(address, result)
        }

    }

    init {
        "init is working".logi(TAG)
    }

    /**
     * todo 优化不使用static xmlMap[XML_REALTIME_FLOAT] 默认都会初始化
     */
    companion object {
        fun getFloatFirst(): DebugDataBean.Item? {
            return if (xmlMap[XML_REALTIME_FLOAT]!!.size != 0) xmlMap[XML_REALTIME_FLOAT]!![0].itemList[0] else null
        }

        fun addReadyList(isLooper: Boolean, readBeans: ArrayList<SocketManagerNew.ReadBean>) {
            var showFloatRealTime = false
            if (DebugDataBean.xmlSettings.contains(XML_XS_RTB) && DebugDataBean.xmlSettings[XML_XS_RTB]!! && floatDataType == "right") {
                showFloatRealTime = true
            } else {
                showFloatRealTime = false
            }
            val floatFirst = getFloatFirst()//realTimeFloat数据组表头
            if (floatFirst != null && showFloatRealTime) {
                //如果该机型文件配置了realTimeFloat
                val bean = SocketManagerNew.ReadBean(
                    (floatFirst.para0.toInt() - 1).toString(),
                    floatFirst.para2,
                    xmlMap[XML_REALTIME_FLOAT]!![0].itemList.size
                )
                SocketManagerNew.addReadyLooperList(isLooper, readBeans.apply { add(bean) })
            } else {
                //如果该机型文件没有配置realTimeFloat
                SocketManagerNew.addReadyLooperList(isLooper, readBeans)
            }
        }
    }
}